import React, { useState, useEffect } from 'react';
import { Input } from 'antd';

import { getValueFromEvent } from '~/utils/polyfill';

export default function (props) {
  const { className, value: propsValue = {}, inputs, onChange: propsChange } = props;

  const [value, setValue] = useState(propsValue);

  const onChange = (code, e) => {
    const v = getValueFromEvent(e);

    const newValue = { ...value, [code]: v };
    setValue(newValue);
    propsChange(newValue, { [code]: v });
  };

  useEffect(() => {
    setValue(propsValue);
  }, [propsValue]);

  return (
    <div className={`comp-form ${className}`}>
      {inputs.map((d) => {
        const { title = '', name, Comp = Input, compProps = {} } = d;

        return (
          <div key={name} className="comp-form-item">
            <div className="comp-form-item-title">{title}</div>
            <Comp {...compProps} value={value[name]} onChange={(...e) => onChange(name, ...e)} />
          </div>
        );
      })}
    </div>
  );
}
